<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel="stylesheet" href="/stylesheets/style.css" />
    <link rel="stylesheet" href="/stylesheets/result.css" />
  </head>
  <body>
    <div class="container">
      <h4 class="crawler-link">目标网站：<%= link %></h4>
      <% if (result && result.length > 0) { %>
      <h4><%= result[0].title %></h4>
      <div>
        <% result[0].labelValuePairs.forEach(function(val, i) { %>
        <div class="crawler-content">
          <span class="label"><%= val.label %>： </span>
          <span class="value"><%= val.value %></span>
        </div>
        <% }) %> <% } %>
      </div>
      <div class="crawler-content-btns">
        <a href="/" class="back-button">返回</a>
        <span class="docx-button" onclick="handleDocx()">生成docx文档</span>
      </div>
    </div>
  </body>
  <script>
    function handleDocx() {
      const resultData = JSON.parse(
        unescape("<%= escape(JSON.stringify(result)) %>")
      );
      const itemId = "<%= itemId %>";
      fetch("/api/download", {
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ data: resultData, itemId: itemId }),
      })
        .then((response) => {
          if (!response.ok) {
            return response.text().then((text) => {
              throw new Error(`请求失败: ${text}`);
            });
          }
          return response.blob();
        })
        .then((blob) => {
          let aLink = document.createElement("a");
          aLink.download = itemId + ".docx";
          aLink.href = URL.createObjectURL(blob);
          aLink.click();
        })
        .catch((error) => console.error("Error:", error));
    }
  </script>
</html>
